package concurrencyCookBook;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;

/**
 * 
 * Exchanger: 只能同步2个线程
 * 	相互之间交换数据
 * 
 */
public class ExchangerDemo {

	public static void main(String[] args) {
		List<String> buffer1=new ArrayList<String>();
		List<String> buffer2=new ArrayList<String>();
		Exchanger<List<String>> exchanger=new Exchanger<List<String>>();
		Producer pd=new Producer(buffer1, exchanger);
		Consumer cs=new Consumer(buffer2, exchanger);
		Thread th1=new Thread(pd);
		Thread th2=new Thread(cs);
		th1.start();
		th2.start();
	}

}

class Producer implements Runnable {
	private List<String> buffer;
	private Exchanger<List<String>> exchanger;

	public Producer(List<String> buffer, Exchanger<List<String>> exchanger) {
		super();
		this.buffer = buffer;
		this.exchanger = exchanger;
	}

	@Override
	public void run() {
		try {
			buffer.add("a1");
			buffer.add("a2");
			buffer = exchanger.exchange(buffer);
			System.out.println("Producer go");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}

class Consumer implements Runnable {
	private List<String> buffer;
	private Exchanger<List<String>> exchanger;

	public Consumer(List<String> buffer, Exchanger<List<String>> exchanger) {
		super();
		this.buffer = buffer;
		this.exchanger = exchanger;
	}

	@Override
	public void run() {
		try {
			buffer.add("b");
			TimeUnit.SECONDS.sleep(10);
			System.out.println("Consumer go");
			buffer = exchanger.exchange(buffer);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(buffer.get(0)+"=======consumer");
	}

}
